// pages/bletool/mainTool_page.js
var ble_master = require('../ble/ble_master.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mac_address: "10:00:00:00:03:89",
    bleServiceUUID: "F000FFF0-0451-4000-B000-000000000000",
    bleCharUUID: "F000FFF1-0451-4000-B000-000000000000",

    getRandom_head: [0x00, 0x84, 0x00, 0x00, 0x08],
    getUTC_head: [0x80, 0xD1, 0x00, 0x00, 0x04],
    setUTC_head: [0x80, 0xD2, 0x00, 0x00, 0x04],

    devices: [],

    dateTime: 0,
  },

  bleStart: function() {
    ble_master.setShowDialogEnable(false)
    this.ble_init()
  },

  ble_init: function () {
    if (ble_master.data.ble_device) {
      if (!ble_master.data.isConnected) {
        ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
      } else {
        this.ble_connectSuccessCallback()
      }
    } else {
      this.ble_foundSpecialDev()
    }
  },

  ble_sendData: function (res) {
    if (ble_master.data.isConnected) {
      ble_master.ble_sendData(res)
    } else {
      console.log("ble device not connect")
    }
  },

  ble_foundSpecialDev: function () {
    ble_master.ble_onDeviceFound(this.christp_foundBluetoothDeviceCallback)
    ble_master.ble_openAdaptorandStartDiscovery()
  },

  christp_afterStopBluetoothDiscovery() {
    // this.christp_jumpToAutoPlantPage()
    console.log("device found")
    ble_master.setShowDialogEnable(true)
    ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
  },

  ble_connectSuccessCallback: function () {
    console.log("Connect to ble device " + ble_master.data.ble_device.deviceId + " success")
    wx.showToast({
      title: 'Connected',
    })
    if (false == ble_master.data.isNotifyOn) {
      ble_master.ble_turnOnNotify(this.data.bleServiceUUID, this.data.bleCharUUID, this.ble_turnOnNotifySuccessCallback)
    } else {
      console.log("the is notify on state is " + ble_master.data.isNotifyOn)
      this.ble_turnOnNotifySuccessCallback()
    }
  },

  ble_turnOnNotifySuccessCallback: function () {
    console.log("Trun on notify success in callback function")
    ble_master.ble_getNotifyData(this.ble_getNotifyDataCallback)

    let cmd = ble_master.connectTwoArrays(ble_master.getCharFromNormalBuffer(this.data.setUTC_head), ble_master.getCharsFromInt(Math.round(new Date() / 1000)))
    console.log(cmd)
    this.ble_sendData(cmd)

  },

  ble_getNotifyDataCallback: function (res) {
    // let str = ble_master.getStringFromBuffer(res)
    console.log("Get notify data: ")
    console.log(res)

    if(res.byteLength == 2) {
      let cmd = ble_master.getCharFromNormalBuffer(this.data.getUTC_head)
      this.ble_sendData(cmd)
    } else if(res.byteLength == 6) {
      let data = ble_master.getIntFromBuffer(res)
      console.log(data)

      let time_date = this.timeStampFormat(data * 1000)

      // wx.showToast({
      //   title: time_date,
      // })
      this.setData({
        dateTime: time_date
      })
    }

    
  },

  timeStampFormat: function (ts) {
    var d = new Date(ts)
    return [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('-')
      + '-'
      + [d.getHours(), d.getMinutes(), d.getSeconds()].join(':')
  },

  

  // Find the device and stop discovery
  christp_foundBluetoothDeviceCallback() {
    this.setData({
      devices: ble_master.data.foundDevices
    })
    // if (ble_master.ble_getDeviceinFoundDeviceListByDeviceID(this.data.mac_address)) {
    //   ble_master.ble_stopDiscovery(this.christp_afterStopBluetoothDiscovery)
    // }
  },

  createBLEConnection: function(e) {
    let devId = e.currentTarget.dataset.deviceId
    console.log(devId)

    if (ble_master.ble_getDeviceinFoundDeviceListByDeviceID(devId)) {
      
      ble_master.ble_stopDiscovery(this.christp_afterStopBluetoothDiscovery)
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})